package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.manager.listener.ExcelCategoryListener;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.manager.service.CategoryService;
import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.excel.ExcelCategoryVo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author syh
 * @create 2023-08-21 13:02
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Resource
    CategoryMapper categoryMapper;
    @Override
    public List<Category> listByParentId(Long pid) {
        List<Category> categories=categoryMapper.selectByParentId(pid);
        categories.forEach(category -> {
            long count=categoryMapper.countChildren(category.getId());
            category.setHasChildren(count>0);
        });
        return categories;
    }
    //导出分类数据
    @Override
    public void exportCates(HttpServletResponse response) {

        try {
            List<Category> categories =categoryMapper.selectList();
            List<ExcelCategoryVo> categoryVos = categories.stream().map(category -> {
                ExcelCategoryVo categoryVo = new ExcelCategoryVo();
                //将category的属性值拷贝给categoryVo对象相同名称+类型的属性
                BeanUtils.copyProperties(category, categoryVo);
                return categoryVo;
            }).collect(Collectors.toList());
            //配置响应头：浏览器/客户端 解析响应之前 可以判断如何读取
            // 设置响应结果类型
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            //设置响应内容描述，告诉浏览器响应的是一个文件+文件名
            String fileName = "spzx_商品分类_"+new DateTime().toString("yyyy-MM-dd")+ ExcelTypeEnum.XLSX.getValue();
            fileName= URLEncoder.encode(fileName,"UTF-8");//为了防止浏览器中文文件名乱码
            response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xlsx");

            //将excel文件写入到响应体中
            EasyExcel.write(response.getOutputStream())//输出流
                    .sheet("商品分类数据")//excel工作簿
                    .head(ExcelCategoryVo.class)//excel表头
                    .doWrite(categoryVos);
        } catch (IOException e) {
            throw new GuiguException(ResultCodeEnum.EXPORT_ERROR);
        }
    }
    //解析excel文件，每一行转为一个分类对象保存到数据库表中
    @Override
    public void importCates(MultipartFile excel) {
        try {
            EasyExcel.read(excel.getInputStream())//解析提交文件的输入流

                    .head(ExcelCategoryVo.class)//表头
                    .registerReadListener(new ExcelCategoryListener(categoryMapper))//注册一个监听器
                    .doReadAll();
        } catch (IOException e) {
            throw new GuiguException(ResultCodeEnum.IMPORT_ERROR);
        }
    }
}
